package org.engine.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.engine.core.ExecuteResult;
import org.engine.core.RuleEngine;
import org.engine.core.RuleEngineContext;
import org.engine.core.RuleFactory;
import org.engine.entity.RuleConfig;
import org.engine.service.IRuleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class RuleServiceImpl implements IRuleService {

    private static final Logger logger = LoggerFactory.getLogger(RuleServiceImpl.class);

    @Autowired
    private RuleEngine ruleEngine;


    @Override
    public void loanALlService() {
        // TODO 从数据库中获取相关配置
        List<RuleConfig> ruleConfigs = new ArrayList<>();
        if (CollectionUtils.isEmpty(ruleConfigs)) {
            return;
        }
        try {
            for (RuleConfig ruleConfig : ruleConfigs) {
                ruleEngine.addRule(ruleConfig.getId(), RuleFactory.parseRule(ruleConfig.getDetail()));
            }
        } catch (Exception e) {
            logger.error("解析规则出错", e);
        }
    }

    @Override
    public void reLoanAllService() {
        ruleEngine.clear();
        loanALlService();
    }

    @Override
    public ExecuteResult execute(String ruleId, JSONObject params) {
        RuleEngineContext ruleEngineContext = new RuleEngineContext(params);
        try {
            return ruleEngine.execute(ruleId, ruleEngineContext);
        } catch (Exception e) {
            logger.error("风控引擎执行出错", e);
            // TODO 具体操作
            return null;
        }
    }
}
